//
//  AppLocale.m
//  storeapp
//
//  Created by huangyi on 12-12-10.
//  Copyright (c) 2012年 ios. All rights reserved.
//

#import "LocalizeMgr.h"
#import "CsvLoader.h"
#import "NSString+path.h"
#import "NSString+urlstring.h"
#import "UIDevice+utils.h"

@interface LocalizeMgr ()

@property(nonatomic,strong)NSMutableDictionary *dictionary;

@end

@implementation LocalizeMgr

+(LocalizeMgr*)shared{
    static LocalizeMgr *singleton=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *langCode=deviceLocaleID().lowercaseString;
        singleton=[[LocalizeMgr alloc] initLocale:langCode];
    });
    return singleton;
}
-(id)initLocale:(NSString*)langCode{
    self=[super init];
    if (self) {
        self.langCode=[NSString stringWithString:langCode];
        [self loadLocale];
    }
    return self;
}

-(void)loadLocale{
    self.dictionary=[NSMutableDictionary dictionaryWithCapacity:1000];
    CsvLoader *loader=[[CsvLoader alloc] init];
    if ([loader loadCsv:LANGFILE.mediaPath]) {
        for (NSDictionary *row in loader.rows) {
            NSString *key=row[@"key"];
            if (key==nil) {
                key=row[@"zh_cn"];
            }
            self.dictionary[key]=row;
        }
    }
    if ([loader loadCsv:LANGFILE.docPath]) {
        for (NSDictionary *row in loader.rows) {
            NSString *key=row[@"key"];
            self.dictionary[key]=row;
        }
    }
}

-(NSString*)localizedString:(NSString*)string{
    NSString *outString=nil;
    if (string.length) {
        outString=self.dictionary[string][self.langCode];
        if (!outString) {
            outString=[NSString stringWithFormat:@"%@",string];
        }
    }else{
        outString=@"LOC_???";
    }
    return outString;
}

-(BOOL)downloadLocale:(NSString*)urlstring{
    BOOL success=NO;
    if (urlstring.length) {
        NSData *override=[NSData dataWithContentsOfURL:[NSURL URLWithString:urlstring]];
        if (override) {
            NSString *filename=LANGFILE.docPath;
            if (filename) {
                success=[filename write:override];
                if (success) {
                    [self loadLocale];
                }
            }
        }
    }
    return success;
}

@end

void LOC_SET(NSString* string){
    LocalizeMgr *loc=[LocalizeMgr shared];
    loc.langCode=string;
}

NSString* LOC_STR(NSString* string){
    LocalizeMgr *loc=[LocalizeMgr shared];
    return [loc localizedString:string];
}
